<script setup lang="ts">
import { ref } from 'vue'
import type { TagProps } from 'ant-design-vue'

interface Props {
  tags: string[]
  color?: TagProps['color']
}

const props = withDefaults(defineProps<Props>(), {
  color: 'purple'
})

const emit = defineEmits<{
  'update:tags': [tags: string[]]
}>()

const inputVisible = ref(false)
const inputValue = ref('')
const inputRef = ref()

const handleClose = (removedTag: string) => {
  const newTags = [...props.tags]
  const index = newTags.indexOf(removedTag)
  if (index !== -1) {
    newTags.splice(index, 1)
    emit('update:tags', newTags)
  }
}

const handleInputConfirm = () => {
  if (inputValue.value && !props.tags.includes(inputValue.value)) {
    const newTags = [...props.tags, inputValue.value.trim()]
    emit('update:tags', newTags)
    }
    inputVisible.value = false
  inputValue.value = ''
}

const showInput = () => {
    inputVisible.value = true
    setTimeout(() => {
    inputRef.value?.focus()
  })
}
</script>

<template>
    <div class="tag-group">
    <a-space size="small" wrap>
            <a-tag
        v-for="tag in tags"
        :key="tag"
        :color="color"
                closable
        class="edit-tag"
        @close="handleClose(tag)"
            >
                {{ tag }}
            </a-tag>
        <a-input
            v-if="inputVisible"
        ref="inputRef"
            v-model:value="inputValue"
        type="text"
            size="small"
        :style="{ width: '78px' }"
        @blur="handleInputConfirm"
            @keyup.enter="handleInputConfirm"
        />
      <a-tag
        v-else
        class="site-tag-plus"
        @click="showInput"
      >
        <template #icon>
          <plus-outlined />
        </template>
        添加标签
      </a-tag>
    </a-space>
    </div>
</template>

<style scoped>
.tag-group {
  padding: 8px 0;
}
.edit-tag {
  user-select: none;
}
.site-tag-plus {
  background: #fff;
  border-style: dashed;
  cursor: pointer;
}
</style>
